<template>
  <div class="chart-container">
    <div ref="chart" style="width: 100%; height: 400px"></div>
  </div>
</template>

<script>
import { getDemoChartData } from '@/api/parkmanagement/report'
import * as echarts from 'echarts'

export default {
  name: 'ParkingChart',
  data() {
    return {
      chartInstance: null
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chartInstance) {
      this.chartInstance.dispose()
    }
  },
  methods: {
    async initChart() {
      try {
        // 初始化图表
        this.chartInstance = echarts.init(this.$refs.chart)
        this.chartInstance.showLoading()

        // 获取数据
        const response = await getDemoChartData()
        const chartData = this.processData(response.data)

        // 配置图表
        const option = {
          title: {
            text: '停车场车辆统计',
            left: 'center'
          },
          tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>车辆数: {c}'
          },
          xAxis: {
            type: 'category',
            data: chartData.parkingNames,
            axisLabel: {
              rotate: 45 // 防止名称过长重叠
            }
          },
          yAxis: {
            type: 'value',
            name: '车辆数'
          },
          series: [{
            name: '车辆数量',
            type: 'bar',
            data: chartData.counts,
            itemStyle: {
              color: '#5470c6' // 柱状图颜色
            }
          }],
          grid: {
            bottom: 100 // 调整底部间距
          }
        }

        this.chartInstance.setOption(option)
        this.chartInstance.hideLoading()
      } catch (error) {
        console.error('加载图表数据失败:', error)
        this.$message.error('数据加载失败')
        this.chartInstance.hideLoading()
      }
    },
    
    // 数据处理
    processData(rawData) {
      // 按停车数量降序排序
      const sortedData = rawData.sort((a, b) => b.totalCount - a.totalCount)
      
      return {
        parkingNames: sortedData.map(item => `停车场 ${item.parkingId}`),
        counts: sortedData.map(item => item.totalCount)
      }
    },
    
    // 窗口变化自适应
    handleResize() {
      if (this.chartInstance) {
        this.chartInstance.resize()
      }
    }
  }
}
</script>